package com.demo.ai.springaidemo.service.chat.impl;

import com.demo.ai.springaidemo.chatUtils.garageSearchTool.SearchToolFunction;
import com.demo.ai.springaidemo.param.ChatParam;
import com.demo.ai.springaidemo.service.chat.ChatService;
import jakarta.annotation.Resource;
import org.apache.groovy.util.Maps;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.tool.function.FunctionToolCallback;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Optional;

/**
 * @author wangbo
 * @date 2025/04/02
 */
@Service
public class ChatServiceImpl implements ChatService {
    @Resource
    private ChatClient chatClient;
    @Override
    public Flux<ServerSentEvent<String>> chatParking(ChatParam param) {

        PromptTemplate promptTemplate = new PromptTemplate("""
                PURPOSE: {purpose}
                """);

        Prompt prompt = promptTemplate.create(Maps.of("purpose", param.getMessage()));
        String content = chatClient.prompt(prompt)
                .tools(new SearchToolFunction())
                .call().content();
//        return chatClient.prompt(prompt)
//                .tools(new SearchToolFunction())
//                .stream().content().map(content -> ServerSentEvent.builder(content).event("message").build())
//                //问题回答结速标识,以便前端消息展示处理
//                .concatWithValues(ServerSentEvent.builder("[DONE]").build())
//                .onErrorResume(e -> Flux.just(ServerSentEvent.builder("Error: " + e.getMessage()).event("error").build()));
        return Flux.just(Optional.ofNullable(content).orElse(""))
                .map(msg -> ServerSentEvent.builder(msg).event("message").build())
                .concatWithValues(ServerSentEvent.builder("[DONE]").event("done").build())
                .onErrorResume(e -> Flux.just(
                        ServerSentEvent.builder("Error: " + e.getMessage()).event("error").build()
                ));
    }
}
